<template>
  <div>
    <!--第一行-->
    <el-row>
      <el-col :span="6">
        <div>
          <el-statistic title="房屋位置">
            <template slot="prefix">
              <i class="el-icon-weizhi statistic-icon"></i>
            </template>
            <template slot="formatter">
              <span class="statistic-text">{{ houseLocation }}</span>
            </template>
          </el-statistic>
        </div>
      </el-col>
      <el-col :span="6">
        <div>
          <el-statistic
              group-separator=","
              :precision="2"
              :value="totalPoint"
              title="当前安全得分"
          >
            <template slot="prefix">
              <i class="el-icon-s-flag statistic-icon" style="color: red"></i>
            </template>
            <template slot="formatter">
              <span class="statistic-text">{{ totalPoint.toFixed(2) }}</span>
            </template>
          </el-statistic>
        </div>
      </el-col>
      <el-col :span="6">
        <div>
          <el-statistic title="本月检查次数" :value="inspectionCount">
            <template slot="formatter">
              <span class="statistic-text">{{ inspectionCount }}</span>
            </template>
          </el-statistic>
        </div>
      </el-col>
      <el-col :span="6">
        <div>
          <el-statistic title="上次检查日期">
            <template slot="formatter">
              <span class="statistic-text">{{ lastInspectionDate }}</span>
            </template>
          </el-statistic>
        </div>
      </el-col>
    </el-row>
    <el-divider></el-divider>
    <!--第二行-->
    <el-row style="display: flex; flex-wrap: wrap; justify-content: center;">
      <!--历史安全得分-->
      <el-col :span="10" style="min-width: 300px;">
        <div id="pointLine" style="width: 100%; height: 320px;"></div>
      </el-col>
      <!-- 通道疏通情况-->
      <el-col :span="4" style="min-width: 300px;">
        <div style="width: 100%; height: 300px; display: flex; justify-content: center; align-items: center;">
          <el-progress type="circle" :percentage="unblockPercent" :format="unblockName" text-color="white"
                       style="border-radius: 50%;" :style="{backgroundColor: unblockColor}"
                       :width="180"></el-progress>
        </div>
      </el-col>
      <!--灭火器-->
      <el-col :span="8" style="min-width: 300px;">
        <el-card style="height: 300px;">
          <strong style="font-size: 18px">灭火器</strong>
          <hr style="margin: 15px 0;">
          <div v-for="(item,index) in description1" :key="index" style="margin: 2px;">
            <i :class="extinguisherStatus[index]?'el-icon-dui':'el-icon-cuowu'"
               :style="{color: extinguisherStatus[index]?'#67C23A':'#F56C6C'}"></i>
            <span> {{ item }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!--第三行-->
    <el-row :gutter="10" style="display: flex; flex-wrap: wrap; justify-content: center;">
      <el-col :span="8" style="min-width: 300px;">
        <el-card style="height: 205px;">
          <strong style="font-size: 18px">烟雾检测器</strong>
          <hr style="margin: 15px 0;">
          <div v-for="(item,index) in description2" :key="index" style="margin: 2px;">
            <i :class="smokeDetectorStatus[index]?'el-icon-dui':'el-icon-cuowu'"
               :style="{color: smokeDetectorStatus[index]?'#67C23A':'#F56C6C'}"></i>
            <span> {{ item }}</span>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8" style="min-width: 300px;">
        <el-card style="height: 205px;">
          <strong style="font-size: 18px">燃气</strong>
          <hr style="margin: 15px 0;">
          <div v-for="(item,index) in description3" :key="index" style="margin: 2px;">
            <i :class="gasStatus[index]?'el-icon-dui':'el-icon-cuowu'"
               :style="{color: gasStatus[index]?'#67C23A':'#F56C6C'}"></i>
            <span> {{ item }}</span>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8" style="min-width: 300px;">
        <el-card style="height: 205px;">
          <strong style="font-size: 18px">电力系统</strong>
          <hr style="margin: 15px 0;">
          <div v-for="(item,index) in description4" :key="index" style="margin: 2px;">
            <i :class="powerStatus[index]?'el-icon-dui':'el-icon-cuowu'"
               :style="{color: powerStatus[index]?'#67C23A':'#F56C6C'}"></i>
            <span> {{ item }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!--第四行-->
    <el-row :gutter="10" style="margin-top: 20px; display: flex; flex-wrap: wrap; justify-content: center;">
      <el-col :span="12" style="min-width: 300px;">
        <el-image :src="evacuationMap"></el-image>
      </el-col>
      <el-col :span="12" style="min-width: 300px;">
        <el-card>
          <strong>总结：</strong>
          <div class="textContent">{{ summary }}</div>
        </el-card>
        <el-card class="aiSuggestion">
          <strong>AI建议：</strong>
          <div class="textContent">{{ aiSuggestion }}</div>
          <div class="generateButton">
            <el-button size="mini" icon="el-icon-edit" type="primary" plain @click="getOwnerAISuggestion">
              <span v-show="aiSuggestion">重新</span>生成建议
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts';

let pointLineOption = {
  title: {
    text: '历史安全得分'
  },
  xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: [65, 32, 77, 81, 46, 88, 92],
      type: 'line',
      smooth: true
    }
  ]
}

export default {
  data() {
    return {
      loginUser: JSON.parse(localStorage.getItem('user')) || {},
      inspectionId: '',
      houseLocation: '',
      totalPoint: 0,
      inspectionCount: 0,
      lastInspectionDate: '',
      pointLineChart: {},
      unblockPercent: 33.3,
      unblockColor: '#67C23A',
      extinguisherStatus: [],
      smokeDetectorStatus: [],
      gasStatus: [],
      powerStatus: [],
      description1: [
        '灭火器铅封完好',
        '灭火器压力良好',
        '灭火器无明显物理损坏',
        '灭火器未过期',
      ],
      description2: [
        '烟雾检测器电池电量充足',
        '烟雾检测器自检功能正常',
        '烟雾检测器无故障报警记录',
      ],
      description3: [
        '燃气管道无泄漏',
        '燃气表读数正常',
        '自动切断阀功能有效',
      ],
      description4: [
        '电路无故障',
        '电气设备绝缘良好',
        '备用电源工作正常',
        '负载分配合理',
        '接地保护完善',
      ],
      evacuationMap: '',
      summary: '',
      aiSuggestion: '',
    }
  },
  mounted() {
    this.getAllData()
    this.loadChart()
  },
  methods: {
    //获取该页面的数据
    getAllData() {
      this.$request.get('/house/house/getSafeStatistics').then(res => {
        if (res.code === 200) {
          this.inspectionId = res.data.inspectionId
          this.houseLocation = res.data.houseLocation
          this.totalPoint = res.data.totalPoint
          this.inspectionCount = res.data.inspectionCount
          this.lastInspectionDate = res.data.lastInspectionDate
          pointLineOption.xAxis.data = res.data.dateList
          pointLineOption.series[0].data = res.data.pointList
          this.unblockPercent = res.data.unblockPercent
          this.extinguisherStatus = res.data.extinguisherStatus
          this.smokeDetectorStatus = res.data.smokeDetectorStatus
          this.gasStatus = res.data.gasStatus
          this.powerStatus = res.data.powerStatus
          this.evacuationMap = res.data.evacuationMap
          this.summary = res.data.summary
          this.aiSuggestion = res.data.aiSuggestion

          this.loadChart()
          if (this.unblockPercent < 40) {
            this.unblockColor = '#F56C6C'
          } else if (this.unblockPercent < 70) {
            this.unblockColor = '#E6A23C'
          } else {
            this.unblockColor = '#67C23A'
          }
        }
      })
    },
    //初始化echarts
    loadChart() {
      //nextTick 是在下次 DOM 更新循环结束之后执行延迟回调，在修改数据之后立即使用 $nextTick，则可以在回调中获取更新后的 DOM。
      //所以使用v-if后能获取到dom元素了
      this.$nextTick(() => {
        // this.myChart?.dispose()
        this.pointLineChart = echarts.init(document.getElementById('pointLine'));

        this.pointLineChart.setOption(pointLineOption);
      })
    },
    //获取分数
    getOwnerPoint() {
      this.$request.get('/user/user/getOwnerPoint').then(res => {
        if (res.code === 200) {
          //总分
          this.totalPoint = res.data.totalPoint
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    unblockName() {
      return '通道疏通情况'
    },
    //获取AI建议
    getOwnerAISuggestion() {
      this.aiSuggestion = ''
      const sse = new EventSource(this.$baseUrl + `/inspection/inspection/owner/aiSuggestion/${this.inspectionId}?token=${this.loginUser.token}`)
      console.log('初始化SSE对象', sse)
      sse.onmessage = event => {
        const message = JSON.parse(event.data).msg
        console.log('收到消息:', message)
        //收到消息实时显示
        this.aiSuggestion = this.aiSuggestion + message
      }
      sse.onerror = event => {
        console.log('sse连接失败', event)
        sse.close()
      }
    },
  }
}
</script>

<style scoped>

.textContent {
  white-space: pre-line;
  margin-top: 0.5em;
}

.generateButton {
  text-align: right;
  margin-top: 0.5em;
}

@media (max-width: 700px) {
  .statistic-text, .statistic-icon {
    font-size: 0.8rem;
    font-weight: bold;
  }
}
</style>
